package com.taiyi.renaissancemall.ui.mine.order.sale.refund;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.taiyi.renaissancemall.R;
import com.taiyi.renaissancemall.Utils.ToastUtils;
import com.taiyi.renaissancemall.base.BaseActivity;
import com.taiyi.renaissancemall.base.MyApp;
import com.taiyi.renaissancemall.bean.FindExpressBean;
import com.taiyi.renaissancemall.bean.OrderDetailBean;
import com.taiyi.renaissancemall.bean.RefundResultBean;
import com.taiyi.renaissancemall.ui.mine.aftersale.AfterSalesActivity;
import com.taiyi.renaissancemall.ui.mine.verified.BaseBottomView;
import com.tencent.mm.opensdk.modelbase.BaseResp;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoActivity;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.OptionPicker;
import cn.qqtheme.framework.picker.SinglePicker;

//退款，退货，换货
public class ApplyRefundActivity extends BaseActivity<ApplyRefundView, ApplyRefundPresent> implements ApplyRefundView, TakePhoto.TakeResultListener, InvokeListener {

    @BindView(R.id.backIv)
    ImageView backIv;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.rightIv)
    ImageView rightIv;
    @BindView(R.id.iv_shop_icon)
    ImageView ivShopIcon;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_shop_size)
    TextView tvShopSize;
    @BindView(R.id.tv_shop_num)
    TextView tvShopNum;
    @BindView(R.id.tv_shop_price)
    TextView tvShopPrice;
    @BindView(R.id.rb_received_goods)
    RadioButton rbReceivedGoods;
    @BindView(R.id.rb_no_received_goods)
    RadioButton rbNoReceivedGoods;
    @BindView(R.id.tv_refund_result)
    TextView tvRefundResult;
    @BindView(R.id.tv_refund_money)
    TextView tvRefundMoney;
    @BindView(R.id.edt_refund_instructions)
    EditText edtRefundInstructions;
    @BindView(R.id.rcl_upload_doc)
    RecyclerView rclUploadDoc;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.ll_upload_doc)
    LinearLayout llUploadDoc;
    @BindView(R.id.rg_refund_status)
    RadioGroup rgRefundStatus;
    @BindView(R.id.ll_refund_money)
    LinearLayout llRefundMoney;
    @BindView(R.id.tv_refund_goods_status)
    TextView tvRefundGoodsStatus;
    @BindView(R.id.top)
    ConstraintLayout top;
    @BindView(R.id.tv_refund_left_result)
    TextView tvRefundLeftResult;
    @BindView(R.id.tv_refund_left_money)
    TextView tvRefundLeftMoney;
    @BindView(R.id.tv_refund_left_context)
    TextView tvRefundLeftContext;
    @BindView(R.id.tv_refund_upload)
    TextView tvRefundUpload;

    private String typeCode = "";
    private String oId;
    private String rStatus = "";//货物状态
    private String rResult = "";//退款原因
    private String rMoney = "";//退款金额
    private String rContext = "";//退款说明
    private String rDocs = "";//退款凭证

    private String get_photo = "";
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private static final String TAG = TakePhotoActivity.class.getName();
    private String mImagePath = Environment.getExternalStorageDirectory() + "";
    private String mImageName = "/wanlimall/" + System.currentTimeMillis() + ".jpg";
    private String path = "";
    private Uri imageUri = null;
    private TextView headChangePopupBlack;
    private Button takePhotoBtn;
    private Button pickPhotoBtn;
    private Button cancelBtn;
    private BaseBottomView bottomView;
    private boolean isXiangCe = false;
    private String iconPath = "";
    private ApplyRefundDocsAdapter applyRefundDocsAdapter;

    private List<String> str_imgList = new ArrayList<>();//凭证集合
    private StringBuffer doc_buffer = new StringBuffer();
    private String eCode = "";//快递公司编码
    private String eName = "";//快递公司名称
    private String ifFlag = "";//2换货用户单号4退货用户快递
    private String getFlag = "";//1 已收到货2 未收到货(returnflag=1时候必传)
    private String getOSSUrl = "";
    private String rFlag = "";//returnflag 1 我要退款（无需退货）2 退货退还 3 换货

    @Override
    protected int getLayoutId() {
        return R.layout.activity_apply_refund;
    }

    @Override
    public ApplyRefundPresent initPresenter() {
        return new ApplyRefundPresent();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);

        typeCode = getIntent().getStringExtra("typeCode");
        oId = getIntent().getStringExtra("oId");

        bottomView = new BaseBottomView(this, R.layout.act_photo);
        headChangePopupBlack = ((TextView) bottomView.findViewById(R.id.headChangePopupBlackId));
        takePhotoBtn = (Button) bottomView.findViewById(R.id.takePhotoBtnId);
        pickPhotoBtn = (Button) bottomView.findViewById(R.id.pickPhtotBtnId);
        cancelBtn = (Button) bottomView.findViewById(R.id.cancel_btnId);
        bottomView.setCancelable(true);

        /*
          1 我要退款
          2 退货退款
          3 换货
          4 填写物流编号
         */
        if ("1".equals(typeCode)) {
            titleTv.setText(getString(R.string.applySale));
            rgRefundStatus.setVisibility(View.VISIBLE);
            llRefundMoney.setVisibility(View.VISIBLE);
            tvRefundGoodsStatus.setVisibility(View.VISIBLE);
            llUploadDoc.setVisibility(View.VISIBLE);
            tvRefundUpload.setVisibility(View.VISIBLE);
            tvRefundGoodsStatus.setText(R.string.goodsStatus);
            tvRefundLeftResult.setText(R.string.refundResult);
            tvRefundLeftMoney.setText(R.string.refundMoney);
            tvRefundLeftContext.setText(R.string.refundInstructions);
            edtRefundInstructions.setHint(R.string.editInstructions);
        } else if ("2".equals(typeCode)) {
            titleTv.setText(getString(R.string.applySale));
            rgRefundStatus.setVisibility(View.GONE);
            llRefundMoney.setVisibility(View.VISIBLE);
            tvRefundGoodsStatus.setVisibility(View.GONE);
            llUploadDoc.setVisibility(View.VISIBLE);
            tvRefundUpload.setVisibility(View.VISIBLE);
            tvRefundLeftResult.setText(R.string.refundGoodsResult);
            tvRefundLeftMoney.setText(R.string.refundGoodsMoney);
            tvRefundLeftContext.setText(R.string.refundGoodsInstructions);
            edtRefundInstructions.setHint(R.string.editGoodsInstructions);
        } else if ("3".equals(typeCode)) {
            titleTv.setText(getString(R.string.applySale));
            llRefundMoney.setVisibility(View.GONE);
            rgRefundStatus.setVisibility(View.GONE);
            tvRefundGoodsStatus.setVisibility(View.GONE);
            llUploadDoc.setVisibility(View.VISIBLE);
            tvRefundUpload.setVisibility(View.VISIBLE);
            tvRefundLeftResult.setText(R.string.refundChangeResult);
            tvRefundLeftContext.setText(R.string.refundChangeInstructions);
            edtRefundInstructions.setHint(R.string.editChangeInstructions);
        } else if ("4".equals(typeCode)) {
            titleTv.setText(getString(R.string.fillOrder));
            llRefundMoney.setVisibility(View.GONE);
            rgRefundStatus.setVisibility(View.GONE);
            llUploadDoc.setVisibility(View.GONE);
            tvRefundUpload.setVisibility(View.GONE);
            tvRefundGoodsStatus.setText(R.string.expressStatus);
            tvRefundLeftResult.setText(R.string.expressCom);
            tvRefundLeftContext.setText(R.string.expressNum);
            edtRefundInstructions.setHint(R.string.editExpressInstructions);
        }

    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(top).init();
    }

    @Override
    protected void initData() {
        showProgress();
        presenter.getOrderDetail(oId);//"1000000000000210"
        //关闭选择界面
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });

        //选择相册
        pickPhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isXiangCe = true;
                imageUri = getImageCropUri();
                //从相册中选取不裁剪
                takePhoto.onPickFromGallery();
            }
        });

        //选择拍照
        takePhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isXiangCe = false;
                imageUri = getImageCropUri();
                //仅仅拍照不裁剪
                takePhoto.onPickFromCapture(imageUri);
            }
        });

        headChangePopupBlack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });
    }

    @Override
    public void initEvent() {

    }

    @Override
    public void getOrderDetailSuccess(OrderDetailBean orderDetailBean) {
        hideProgress();
        getFlag = orderDetailBean.getOrder().getFlag();
        rFlag = orderDetailBean.getOrder().getReturnflag();
        if (!"".equals(orderDetailBean.getOrder().getImgurl())
                && orderDetailBean.getOrder().getImgurl() != null) {
            Glide.with(ApplyRefundActivity.this).load(orderDetailBean.getOrder().getSmallimgurl()).into(ivShopIcon);
        }
        String sName = "";
        if (orderDetailBean.getOrder().getName().contains("\r\n")) {
            sName = orderDetailBean.getOrder().getName().replace("\r\n", "");
        } else {
            sName = orderDetailBean.getOrder().getName();
        }
        tvShopName.setText(sName);
        tvShopSize.setText(orderDetailBean.getOrder().getTypename());
        String sNum = "X" + orderDetailBean.getOrder().getNumber();
        tvShopNum.setText(sNum);
        tvShopPrice.setText(orderDetailBean.getOrder().getSumprice());
        tvRefundMoney.setText(orderDetailBean.getOrder().getSumprice());
        rMoney = orderDetailBean.getOrder().getSumprice();
    }

    @Override
    public void getOrderDetailFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void getRefundResultSuccess(RefundResultBean refundResultBean) {
        hideProgress();

        List<RefundResultBean.ListBean> list = refundResultBean.list;
        List<String> strings = new ArrayList<>();
        for (RefundResultBean.ListBean listBean : list) {
            strings.add(listBean.name);
        }
        SinglePicker<String> listBeanSinglePicker = new SinglePicker<>(this, strings);
        listBeanSinglePicker.setTextSize(18);
        listBeanSinglePicker.setHeight((int) (getResources().getDisplayMetrics().heightPixels * 0.4));
        listBeanSinglePicker.show();
        listBeanSinglePicker.setOnItemPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                tvRefundResult.setText(item);
                rResult = item;
            }
        });
    }

    @Override
    public void getRefundResultFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void toApplyRefundSuccess(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
        startActivity(new Intent(this, AfterSalesActivity.class));
        finish();
    }

    @Override
    public void toApplyRefundFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @Override
    public void editExpressSuccess(String msg) {
        hideProgress();
        ToastUtils.showShortToast(msg);
        finish();
    }

    @Override
    public void editExpressFailure(String msg) {
        hideProgress();
        ToastUtils.showShortToast(msg);
    }

    @Override
    public void findExpressSuccess(List<FindExpressBean> findExpressBean) {
        hideProgress();

        List<FindExpressBean> list = findExpressBean;
        List<String> strings = new ArrayList<>();
        for (FindExpressBean listBean : list) {
            strings.add(listBean.expressname);
        }
        SinglePicker<String> listBeanSinglePicker = new SinglePicker<>(this, strings);
        listBeanSinglePicker.setTextSize(18);
        listBeanSinglePicker.setHeight((int) (getResources().getDisplayMetrics().heightPixels * 0.4));
        listBeanSinglePicker.show();
        listBeanSinglePicker.setOnItemPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int index, String item) {
                tvRefundResult.setText(item);
                eName = item;
                eCode = findExpressBean.get(index).expresscode;
            }
        });

    }

    @Override
    public void findExpressFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @OnClick({R.id.backIv, R.id.rb_received_goods, R.id.rb_no_received_goods, R.id.tv_refund_result, R.id.btn_commit, R.id.ll_upload_doc})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backIv:
                finish();
                break;
            case R.id.rb_received_goods:
                rStatus = "2";
                rbReceivedGoods.setSelected(true);
                rbNoReceivedGoods.setSelected(false);
                break;
            case R.id.rb_no_received_goods:
                rStatus = "1";
                rbReceivedGoods.setSelected(false);
                rbNoReceivedGoods.setSelected(true);
                break;
            case R.id.tv_refund_result:
                showProgress();
                if ("4".equals(typeCode)) {
                    presenter.findExpress();
                } else {
                    presenter.getRefundResult();
                }
                break;
            case R.id.ll_upload_doc:
                bottomView.show();
                break;
            case R.id.btn_commit:
                rContext = edtRefundInstructions.getText().toString().trim();
                //填写物流单号
                if ("4".equals(typeCode)) {
                    if ("2".equals(rFlag)) {
                        ifFlag = "4";
                    } else if ("3".equals(rFlag)) {
                        ifFlag = "2";
                    }
                    if (TextUtils.isEmpty(eName)) {
                        ToastUtils.showLongToast("请选择快递公司");
                        return;
                    }
                    if (TextUtils.isEmpty(rContext)) {
                        ToastUtils.showLongToast("请填写快递编号");
                        return;
                    }
                    showProgress();
                    presenter.toEditExpress(oId, eName, rContext, eCode, ifFlag);
                } else {
                    rDocs = doc_buffer.toString().trim();//凭证
                    if (doc_buffer.toString().trim().endsWith(",")) {
                        rDocs = doc_buffer.toString().trim().substring(0, doc_buffer.toString().trim().length() - 1);
                    }
                    /*
                      1 我要退款
                      2 退货退款
                      3 换货
                      4 填写物流编号
                     */
                    if ("1".equals(typeCode)) {
                        if (TextUtils.isEmpty(rStatus)) {
                            ToastUtils.showShortToast("请勾选是否收到货");
                            return;
                        }
                    }
                    if (TextUtils.isEmpty(rResult)) {
                        ToastUtils.showShortToast("请选择退换原因");
                        return;
                    }
                    if (TextUtils.isEmpty(rContext)) {
                        ToastUtils.showShortToast("请填写退换说明");
                        return;
                    }
                    if ("2".equals(rStatus)
                            || "2".equals(typeCode)
                            || "3".equals(typeCode)) {
                        if (TextUtils.isEmpty(rDocs)) {
                            ToastUtils.showShortToast("请上传凭证");
                            return;
                        }
                    }
                    showProgress();
                    presenter.toApplyRefund(oId, rResult, rStatus, rContext, rDocs, typeCode);
                }
                break;
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        if (bottomView.isShowing()) {
            bottomView.dismiss();
        }
        iconPath = result.getImage().getOriginalPath();
        if (isXiangCe) {
            uploadFileToOSS(iconPath);
        } else {
            uploadFileToOSS(path);
        }
        Log.i(TAG, "takeSuccess：" + result.getImage().getCompressPath() + "==" + result.getImage().getOriginalPath());

    }

    /**
     * 凭证列表
     *
     * @param str_imgList
     */
    private void setAdapter(List<String> str_imgList) {
        rclUploadDoc.setVisibility(View.VISIBLE);
        applyRefundDocsAdapter = new ApplyRefundDocsAdapter(R.layout.layout_uplode_doc, str_imgList);
        rclUploadDoc.setLayoutManager(new GridLayoutManager(ApplyRefundActivity.this, 3));
        rclUploadDoc.setAdapter(applyRefundDocsAdapter);
        applyRefundDocsAdapter.notifyDataSetChanged();
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File file = new File(mImagePath, mImageName);
        path = mImagePath + mImageName;
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }

    private void uploadFileToOSS(String iconPath) {
        String[] strings = iconPath.split("/");
        String name = strings[strings.length - 1];
        OSSClient ossClient = MyApp.getOssClient();
        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest("wlshop-app", name, iconPath);

        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = ossClient.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("PutObject", "UploadSuccess");
                        Log.d("ETag", result.getETag());
                        Log.d("RequestId", result.getRequestId());
                        getOSSUrl = ossClient.presignPublicObjectURL("wlshop-app", name);
                        Log.d("servercallback", "1--" + getOSSUrl);
                        get_photo = getOSSUrl;
                        //将图片传给列表
                        str_imgList.add(get_photo);
                        if (str_imgList.size() == 6) {
                            llUploadDoc.setVisibility(View.GONE);
                        }
                        doc_buffer.append(get_photo);
                        doc_buffer.append(",");
                        setAdapter(str_imgList);
                    }
                });
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                ToastUtils.showLongToast("图片上传异常");
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务。
        // task.waitUntilFinished(); // 等待任务完成。
    }

}
